package models;

import helpers.GeneralHelper;
import helpers.StringHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

import entities.Category;

public class CategoryModel {
	
	private Objectify ofy;

	private Cache cache = null;

	private String prefix = "category_";

	private static CategoryModel instance = null;
	
	public static CategoryModel getInstance() {
		if (instance == null) {
			instance = new CategoryModel();
		}
		
		return instance;
	}
	
	private CategoryModel() {
		try {
			ObjectifyService.register(Category.class);
		} catch (Exception e) {
			// e.printStackTrace();
		}
		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}

	public List<Category> getAll() {
		List<Category> categories = new ArrayList<Category>();
		
		String cacheName = prefix + "list_all";
		boolean isCached = false;
		
		if (cache != null) {
			try {
				categories = (List<Category>) cache.get(cacheName);
				if (categories != null) isCached = true;
			} catch (Exception e) {
			}			 
		}
		
		if (!isCached) {
			categories = ofy.query(Category.class).list();
			
			if (cache != null) {
				cache.put(cacheName, categories);
			}
		}
		

		return categories;
	}

	public Category getCategory(String id) {
		Category category = new Category();
		
		try {
			category = ofy.get(new Key<Category>(Category.class, id));
		} catch (Exception e) {
			category = null;
		}
		return category;
	}

	public Category getCategoryByAlias(String alias) {
		Category category = new Category();
		
		String cacheName = prefix + "_alias_" + alias;
		boolean isCached = false;
		
		if (cache != null) {
			try {
				category = (Category) cache.get(cacheName);
				if (category != null) isCached = true;
			} catch (Exception e) {
			}
		} 
		
		if (!isCached) {
			try {
				category = ofy.query(Category.class).filter("alias", alias).get();
				if (cache != null && category != null) {
					cache.put(cacheName, category);
				}
			} catch (Exception e) {
				category = null;
			}
				
		}
		
		return category;
	}
	
	public Map<String, Category> getByListId(List<String> ids) {
		Map<String, Category> categories = new TreeMap<String, Category>();
		
		categories = ofy.get(Category.class, ids);
		
		return categories;
	}
	
}
